package org.example.hospital_frontend.controller;

import org.apache.commons.lang3.StringUtils;
import org.example.hospital_frontend.common.BaseResponse;
import org.example.hospital_frontend.common.ErrorCode;
import org.example.hospital_frontend.common.ResultUtils;
import org.example.hospital_frontend.domain.User;
import org.example.hospital_frontend.exception.BusinessException;
import org.example.hospital_frontend.mapper.UserMapper;
import org.example.hospital_frontend.request.UserLoginRequest;
import org.example.hospital_frontend.request.UserRegisterRequest;
import org.example.hospital_frontend.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        String username = userRegisterRequest.getUsername();
        String password = userRegisterRequest.getPassword();
        Long role = userRegisterRequest.getRole();
        Long gender = userRegisterRequest.getGender();
        String nickname = userRegisterRequest.getNickname();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(username, password, checkPassword)) {
            return null;
        }
        if (role==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户身份不明");
        }
        long result = userService.userRegister(username, password, checkPassword,role, gender,nickname);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest httpServletRequest) {
        String userAccount = userLoginRequest.getUsername();
        String password = userLoginRequest.getPassword();
        Long userRole = userLoginRequest.getRole();
        if (userRole==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户身份不明");
        }
        if (StringUtils.isAnyBlank(userAccount, password)) {
            return null;
        }
        return ResultUtils.success(userService.doLogin(userAccount, password, userRole,httpServletRequest));
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return ResultUtils.success(userMapper.selectById(currentUser.getId()));
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody User user, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        user.setId(currentUser.getId());
        boolean result = userService.updateById(user);
        if (result) {
            // 更新session中的用户信息
            request.getSession().setAttribute("USER_LOGIN_STATE", user);
        }
        return ResultUtils.success(result);
    }

    @PostMapping("/upload/avatar")
    public BaseResponse<String> uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件为空");
        }
        
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        
        // 生成新的文件名
        String fileName = UUID.randomUUID().toString() + suffix;
        
        // 指定上传目录
        String uploadDir = request.getServletContext().getRealPath("./res/uploads/avatars/");
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        // 保存文件
        File dest = new File(uploadDir + fileName);
        try {
            file.transferTo(dest);
            
            // 更新用户头像URL
            String avatarUrl = "./res/uploads/avatars/" + fileName;
            User user = new User();
            user.setId(currentUser.getId());
            user.setAvatar(avatarUrl);
            userService.updateById(user);
            
            // 更新session中的用户信息
            currentUser.setAvatar(avatarUrl);
            request.getSession().setAttribute("USER_LOGIN_STATE", currentUser);
            
            return ResultUtils.success(avatarUrl);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        }
    }
}
